#include <stdio.h>
#include <getopt.h>

#include "../util.h"
#include "../verb/pageinfo.h"
#include "../action/pageinfo.h"

_Noreturn void verb_pageinfo_usage(FILE *restrict out) {
    fputs("Usage: " PROGRAM_NAME " pageinfo [OPTIONS]\n", out);
    fputs("Fetch the infomation of the login page and parse it.\n", out);
    fputs("Host is required.\n", out);
    fputs("\n", out);
    fputs("Options:\n", out);
    fputs("  --help                     display this help and exit\n", out);
    fputs("\n", out);
    fputs("Exit status:\n", out);
    fputs(" 0  if successfully fetched and parsed\n", out);
    fputs(" 1  if unable to parse arguments\n", out);
    fputs(" 2  if unable to fetch infomation\n", out);
    fputs(" 3  if unable to parse infomation\n", out);
    exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
}

int verb_pageinfo(const int argc, char* const* argv) {
    int lose = 0;
    static struct option long_options[] = {
        {"help",      no_argument,  NULL, 'h' },
        {0,           0,                  0,     0 }
    };
    
    while (1) {
        int c = getopt_long(argc, argv, "h", long_options, NULL);

        if (c == -1) {
            break;
        }

        switch (c) {
            case 'h':
                verb_pageinfo_usage(stdout);
                break;

            default:
                lose = 1;
                break;
        }
    }
    
    if (lose) {
        verb_pageinfo_usage(stderr);
        exit(EXIT_FAILURE);
    }
    
    if (optind < argc) {
        error(0, 0, "Too many arguments.\n");
        verb_pageinfo_usage(stderr);
        exit(EXIT_FAILURE);
    }
    
    if (GLOBAL_ARGS.portal_host == NULL) {
        error(0, 0, "No host provided.");
        exit(EXIT_FAILURE);
    }
    
    action_pageinfo_result result = action_pageinfo(
        GLOBAL_ARGS.bind_interface,
        GLOBAL_ARGS.portal_host,
        GLOBAL_ARGS.portal_search
    );
    
    if (result.status == ACTION_FETCHING_FAILURE) {
        return 2;
    }
    
    if (result.status == ACTION_PAGEINFO_PARSE_FAILURE) {
        return 3;
    }
    
    if (result.passwordEncrypt) {
        puts("passwordEncrypt: true");
        if (result.publicKeyExponent != NULL) {
            printf("publicKeyExponent: %s\n", result.publicKeyExponent);
        }
        if (result.publicKeyModulus != NULL) {
            printf("publicKeyModulus: %s\n", result.publicKeyModulus);
        }
    } else {
        puts("passwordEncrypt: false");
    }
    return 0;
}
